<?php


namespace app\common\lib\live;


use app\chat\LiveMessage;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\lib\Util;
use GatewayWorker\Lib\Gateway;
use think\Env;
use think\queue\Job;

class LiveCloseJob
{
    /**
     * 关闭直播
     * @param Job $job
     * @param $jobData
     */
    public function task(Job $job, $jobData)
    {
        // $jobData = [
        //     'live_id' => 10186336,
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }
        $registerAddress = config('websocket.register_ip') . ':' . config('websocket.register_port');

        Gateway::$registerAddress = $registerAddress;
        $liveClient = Gateway::getClientSessionsByGroup($jobData['live_id'] . '_liver_or_admin');

        foreach ($liveClient as $item)
        {
            if ($item['user_type'] == 1)
            {
                $job->delete();  // 直播进行中
                return;
            }
        }

        $liveRecordModel = new LiveRecordingInfo();
        // 关闭直播记录关闭
        $data = $liveRecordModel->where('live_id', $jobData['live_id'])->where('status', 1)->find();

        if ($data)
        {
            $liveDuration = ceil((time() - $data['live_start_time']) / 60) - 5; // 直播时长 分钟

            (new LiveRecordingInfo())->updateData($data['id'], [
                'status' => 2,
                'live_duration' => $liveDuration > 0 ? $liveDuration : 0,
                'close_time' => time(),
                'close_use_type' => 3,
                'close_uid' => 0
            ]);

            $env = Env::get('host.name', 'local');
            $this->sendMsg('[' . $env . ']直播异常关闭',
                "# 直播异常端口5分钟内未重连关闭直播 \r\n\r\n " .
                "环境：{$env} \r\n\r\n " .
                "直播间：{$jobData['live_id']} \r\n\r\n " .
                "直播时长：{$liveDuration} \r\n\r\n " .
                "关播时间：".date('Y-m-d H:i:s'),
                '');
            // 发送关播消息
            // 向用户发送关播消息
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ALL, $jobData['live_id'], $jobData['live_id']), LiveMessage::MSG_TYPE_LIVE_STATUS, 1);
        }

        $job->delete();
    }

    private function sendMsg($title, $contentMsg, $herfUrl)
    {
        $time = time() * 1000;
        // PHP钉钉群
        $sec = 'SECcd9cc7f9e863073d9ebd0a2d0c9ed2f38d38ffcd67b700866d97ab3f919eb419';
        $sign = urldecode(base64_encode(hash_hmac('sha256', $time . "\n" . $sec, $sec, true)));
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=b93977081e77642ab22db0e369abc12e08389a99441b3cc2ed6b3f675d8e9d7e';// 钉钉推送地址

        $url .= "&timestamp={$time}&sign={$sign}";

        Util::sendDingMsg($url, $title, $contentMsg, 3, $herfUrl);
    }
}
